<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\BaseController;
use app\admin\model\Article as ArticleList;
use app\admin\model\ArticleCate;
use app\admin\model\Keywords;
use app\admin\validate\ArticleCateCheck;
use app\admin\validate\ArticleCheck;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Article extends BaseController
{
    public function cate()
    {
        return view();
    }

    //文章分类列表
    public function cate_list()
    {
        $cate = Db::name('ArticleCate')->order('create_time asc')->select();
        return to_assign(0, '', $cate);
    }

    //文章分类添加
    public function cate_add()
    {
        return view('', ['pid' => get_params('pid')]);
    }

    //提交保存文章分类
    public function cate_post_submit()
    {
        if (request()->isAjax()) {
            $param = get_params();
            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(ArticleCateCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(0, $e->getError());
                }
                $data[$param['field']] = $param['value'];
                $data['id'] = $param['id'];
                $data['update_time'] = time();
                $res = ArticleCate::strict(false)->field(true)->update($data);
                if ($res) {
                    add_log('edit', $data['id'], $data);
                }

                return to_assign();
            } else {
                try {
                    validate(ArticleCateCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(0, $e->getError());
                }
                $param['create_time'] = time();
                $insertId = ArticleCate::strict(false)->field(true)->insertGetId($param);
                if ($insertId) {
                    add_log('add', $insertId, $param);
                }

                return to_assign();
            }
        }
    }

    //删除文章分配
    public function cate_delete()
    {
        $id = get_params("id");
        $cate_count = Db::name('ArticleCate')->where(["pid" => $id])->count();
        if ($cate_count > 0) {
            return to_assign(0, "该分类下还有子分类，无法删除");
        }
        $content_count = Db::name('Article')->where(["article_cate_id" => $id])->count();
        if ($content_count > 0) {
            return to_assign(0, "该分类下还有文章，无法删除");
        }
        if (Db::name('ArticleCate')->delete($id) !== false) {
            add_log('delete', $id);
            return to_assign(1, "删除分类成功");
        } else {
            return to_assign(0, "删除失败");
        }
    }

    public function index()
    {
        return view();
    }

    //文章列表
    public function get_list()
    {
        $param = get_params();
        $where = array();
        if (!empty($param['keywords'])) {
            $where[] = ['a.id|a.title|a.keywords|a.desc|a.content|w.title', 'like', '%' . $param['keywords'] . '%'];
        }
        if (!empty($param['article_cate_id'])) {
            $where[] = ['a.article_cate_id', '=', $param['article_cate_id']];
        }
        $where[] = ['a.status', '>=', 0];
        $rows = empty($param['limit']) ? get_config(app . page_size) : $param['limit'];
        $content = ArticleList::where($where)
            ->field('*,w.id as cate_id,a.id as id,w.title as cate_title,a.title as title')
            ->alias('a')
            ->join('article_cate w', 'a.article_cate_id = w.id')
            ->order('a.create_time desc')
            ->paginate($rows, false, ['query' => $param]);
        return table_assign(1, '', $content);
    }

    //文章添加&&编辑
    public function add()
    {
        $id = empty(get_params('id')) ? 0 : get_params('id');
        View::assign('id', $id);
        if ($id > 0) {
            $article = (new ArticleList())->detail($id);
            View::assign('article', $article);
            return view('edit');
        }
        return view();
    }

    //文章内容提交保存
    public function post_submit()
    {
        if (request()->isAjax()) {
            $param = get_params();
			$DbRes=false;
            if (!empty($param['id']) && $param['id'] > 0) {
                try {
                    validate(ArticleCheck::class)->scene('edit')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(0, $e->getError());
                }
                $param['update_time'] = time();
				
				Db::startTrans();
                try {
					$res = ArticleList::strict(false)->field(true)->update($param);						
					$aid = $param['id'];
					if ($res) {
						Db::name('ArticleKeywords')->where(['aid'=>$aid])->delete();
						if (isset($param['keyword_names']) && $param['keyword_names']) {
							$keywordArray = explode(',', $param['keyword_names']);
							foreach ($keywordArray as $key => $value) {
								if (!$value) {
									continue;
								}
								$data = [];
								$data['aid'] = $aid;
								$keywords_id = (new Keywords())->increase($value);
								$data['keywords_id'] = $keywords_id;
								$data['create_time'] = time();
								Db::name('ArticleKeywords')->strict(false)->field(true)->insertGetId($data);
							}
						}
						add_log('edit', $param['id'], $param);
						Db::commit();
						$DbRes=true;
					} else {
                         Db::rollback();
                    }
                }
                catch (\Exception $e) { ##这里参数不能删除($e：错误信息)
                     Db::rollback();
                }
            } else {
                try {
                    validate(ArticleCheck::class)->scene('add')->check($param);
                } catch (ValidateException $e) {
                    // 验证失败 输出错误信息
                    return to_assign(0, $e->getError());
                }
                $param['create_time'] = time();
                Db::startTrans();
                try {
                    $aid = ArticleList::strict(false)->field(true)->insertGetId($param);
                    if ($aid) {
                        if (isset($param['keyword_names']) && $param['keyword_names']) {
                            $keywordArray = explode(',', $param['keyword_names']);
                            foreach ($keywordArray as $key => $value) {
								if (!$value) {
									continue;
								}
								$data = [];
								$data['aid'] = $aid;
								$keywords_id = (new Keywords())->increase($value);
								$data['keywords_id'] = $keywords_id;
								$data['create_time'] = time();
								Db::name('ArticleKeywords')->strict(false)->field(true)->insertGetId($data);
							}
                        }
                        add_log('add', $aid, $param);
                        Db::commit();
                        $DbRes=true;
                    } else {
                         Db::rollback();
                    }
                }
                catch (\Exception $e) { ##这里参数不能删除($e：错误信息)
                     Db::rollback();
                }
            }
			if($DbRes){
				return to_assign();
			}
			else{
				return to_assign(0,'操作失败');
			}
        }
    }

    //删除文章
    public function delete()
    {
        $id = get_params("id");
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        if (Db::name('Article')->update($data) !== false) {
            add_log('delete', $id);
            return to_assign(1, "删除成功");
        } else {
            return to_assign(0, "删除失败");
        }
    }
}
